package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.TreeMap;

import model.Cart;
import model.Item;

public class SuccessOrderData {
	public static void addItemSuccess(long idItem , String nameItem , String email , int quantityItem){
		Connection con = DbConnection.getConnect();
		String sql = "INSERT INTO successorder VALUES(?,?,?,?)";
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			pre.setString(2, nameItem);
			pre.setString(3, email);
			pre.setInt(4, quantityItem);
			pre.executeUpdate();
			pre.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static int getQuantityItem(long idItem , String email){
		Connection con = DbConnection.getConnect();
		String sql = "SELECT * FROM successorder WHERE item_idItem = ? AND user_email = ? ";
		int quantityItem =0;
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			pre.setString(2, email);
			  ResultSet rs = pre.executeQuery();
			  
			while(rs.next()){
				 quantityItem = rs.getInt("quantityItem");
			}
			pre.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		
		return quantityItem;
		
	}
	public static void AddListCart(Cart cart , String email){
		
		
		TreeMap<Item ,Integer> list = cart.getListItem();
		Iterator<Item> key = list.keySet().iterator();
		while (key.hasNext()) {
			
			Item k = key.next();
			int quantityItem = list.get(k); 
			long idItem =k.getIdItem();
			int q = getQuantityItem(idItem, email);
			String nameItem = k.getNameItem();
			delItemCart(idItem, email);
			addItemSuccess(idItem, nameItem, email, q+quantityItem);
			
		}
		
	}
	public static void delItemCart(long idItem , String email){
		Connection con = DbConnection.getConnect();
		String sql = "DELETE FROM successorder WHERE item_idItem = ? AND user_email = ?";
		PreparedStatement pre;

		try {
			pre = con.prepareStatement(sql);
			pre.setLong(1, idItem);
			pre.setString(2, email);
			pre.executeUpdate();
			pre.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		delItemCart(19, "bongma@zing.vn");
	}

}
